package com.alinesno.cloud.common.web.login.dialect.processor;

import static org.thymeleaf.util.Validate.notEmpty;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.AbstractAttributeTagProcessor;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.spring5.context.SpringContextUtils;
import org.thymeleaf.templatemode.TemplateMode;

import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.base.boot.enums.RolePowerTypeEnmus;
import com.alinesno.cloud.common.web.login.session.CurrentAccountSession;

/**
 * 是否有编辑权限，编辑权限包括页面搜索框编辑和按钮权限编辑
 * @author WeiXiaoJin
 * @since 2019年10月4日 下午4:56:19
 */
public class HasEditAttrProcessor extends AbstractAttributeTagProcessor {

	private static final Logger log = LoggerFactory.getLogger(HasEditAttrProcessor.class) ; 
	
    private static final String ATTRIBUTE_NAME = "hasEdit";
    private static final int PRECEDENCE = 300;

    public HasEditAttrProcessor(String dialectPrefix) {
        super(TemplateMode.HTML,dialectPrefix, null,false, ATTRIBUTE_NAME, true, PRECEDENCE, true); 
    }

    @SuppressWarnings("unused")
	@Override
    protected void doProcess(ITemplateContext iTemplateContext,
                             IProcessableElementTag iProcessableElementTag,
                             AttributeName attributeName,
                             String attributeValue,
                             IElementTagStructureHandler iElementTagStructureHandler) {

    	log.debug("attribute name:{} ,  value:{}" , attributeName.getAttributeName() , attributeValue);
        notEmpty(attributeValue , "value of '" + ATTRIBUTE_NAME + "' must not be empty");
    	
    	ApplicationContext ctx = SpringContextUtils.getApplicationContext(iTemplateContext);
    	CurrentAccountSession currentAccountSession = ctx.getBean(CurrentAccountSession.class) ; 
    	
    	ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    	HttpServletRequest request = requestAttributes.getRequest();
    
    	ManagerAccountEntity account = currentAccountSession.get(); 
    	String edit =account.getHasEditor() ;
    	
    	String menuId = request.getParameter("menuId") ; 
    	
    	
    	
    	if(!RolePowerTypeEnmus.ROLE_EDIT.value.equals(edit)) {  // 用户没有编辑权限
    		iElementTagStructureHandler.removeElement();
    	}
    	
//    	iElementTagStructureHandler.removeAttribute(ATTRIBUTE_NAME); 
    	
    }
}